﻿#include "Scene0917.h"


Scene* Scene0917::createScene()
{
	return Scene0917::create();
}

bool Scene0917::init()
{
	if (!Scene::init())
	{
		return false;
	}

	// 加载素材
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("GameSence.plist",
		"GameSence.png");

	//注册触屏事件
	EventListenerTouchOneByOne * listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = CC_CALLBACK_2(Scene0917::onTouchBegin,this);
	listener->onTouchMoved = CC_CALLBACK_2(Scene0917::onTouchMoved,this);
	
	//把这个listener加入到事件派发器里
	Director::getInstance()->getEventDispatcher()->
		addEventListenerWithSceneGraphPriority(listener, this);



	//游戏背景
	Sprite * bg = Sprite::create("res/Background.png");
	bg->setPosition(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2);
	bg->setScale(VISIBLE_SIZE.height/ bg->getBoundingBox().size.height);
	addChild(bg);

	//出牌按钮
	Sprite * discard_normal = Sprite::createWithSpriteFrameName("youxi13.png");
	Sprite * discard_selected = Sprite::createWithSpriteFrameName("youxi18.png");
	Sprite * discard_disabled = Sprite::createWithSpriteFrameName("youxi14.png");

	MenuItemSprite * discardItem = MenuItemSprite::create(discard_normal, discard_selected,
		discard_disabled,CC_CALLBACK_1(Scene0917::judgeItemClicked,this));
	discardItem->setScale(0.5);
	discardItem->setPositionY(-50);
	discardItem->setTag(1);
	discardItem->setVisible(false);
	
	//关闭游戏场景按钮
	MenuItemImage * closeItem = MenuItemImage::create("CloseSelected.png", "CloseNormal.png");

	closeItem->setCallback(CC_CALLBACK_1(Scene0917::close,this));

	closeItem->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
	closeItem->setPosition(-VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2);
	closeItem->setScale(2);
	//
	// 开始游戏按钮
	Button *beginButton = Button::create("res/begin_normal.png");
	beginButton->setPosition(Vec2(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2 - 50));
	beginButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::beginGame, this));
	addChild(beginButton);

	Menu *menu = Menu::create(closeItem, discardItem, NULL);
	menu->setTag(300);
	addChild(menu);

	CommonFunction::getChineseWithKey("a");

	//创建4个玩家
	self_pos = 3;
	{
		player_self->accout = StringUtils::format("player3");
		player_self->position = 3;
		loadPlayerUI(player_self);

		player_left->accout = StringUtils::format("player2");
		player_left->position = 2;
		loadPlayerUI(player_left);

		player_front->accout = StringUtils::format("player1");
		player_front->position = 1;
		loadPlayerUI(player_front);

		player_right->accout = StringUtils::format("player4");
		player_right->position = 4;
		loadPlayerUI(player_right);
	}

	//创建按钮Button  创建晒红十按钮
	Button * showButton = Button::create("res/show_normal.png");
	showButton->setPosition(Vec2(VISIBLE_SIZE.width / 2-100, VISIBLE_SIZE.height / 2+50));
	showButton->setTag(100);
	showButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	showButton->setScale(0.8f);
	addChild(showButton);
	//创建按钮Button  创建不晒红十按钮
	Button * unShowButton = Button::create("res/unshow_normal.png");
	unShowButton->setPosition(Vec2(VISIBLE_SIZE.width / 2+100, VISIBLE_SIZE.height / 2 +50));
	unShowButton->setTag(200);
	unShowButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	unShowButton->setScale(0.8f);
	addChild(unShowButton);

	showButton->setVisible(false);
	unShowButton->setVisible(false);

	return true;
}


//按钮点击事件
void Scene0917::judgeItemClicked(Ref * sender)
{
	//首先获取选择的牌是什么
	vector<int> arr;
	//遍历一遍牌精灵，看看哪些牌弹出了
	for (int i = 0; i < player_self->countCards(); i++)
	{
		Node * card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
		if (card_node->getPositionY() > cardOriginY)
		{
			arr.push_back(player_self->cards[i]);

		}
	}
	//检验下
	for (int i = 0; i < arr.size(); i++)
	{
		log("%d", arr[i]);
	}
	//然后判断牌型是什么
	PokerType type = game->getPokerTypeWithCards(arr);
	switch (type)
	{
	case POKER_TYPE_SINGLE:
		log("danpai");
		break;
	case POKER_TYPE_DOUBLE:
		log("duizi");
		break;
	case POKER_TYPE_KING_BOMB:
		log("wangzha");
		break;
	case POKER_TYPE_REDTEN_BOMB:
		log("shuanghongshi");
		break;
	case POKER_TYPE_THREE_BOMB:
		log("sanzhangzhadan");
		break;
	case POKER_TYPE_FOUR_BOMB:
		log("sizhangzhadan");
		break;
	case POKER_TYPE_STRAIGHT:
		log("shunzi");
		break;
	default: 
		log("ERROR!");
		break;
	}

	if (type > 0)
	{
		//把玩家手中的牌移到中间
		Vec2 cardsMove = Vec2(VISIBLE_SIZE.width / 2 - 120, VISIBLE_SIZE.height / 2);//定义一个向量储存中间区域的位置
		for (int i = 0; i < player_self->countCards(); i++)
		{
			Node * card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			if (card_node->getPositionY() > cardOriginY)
			{
				card_node->setPosition(cardsMove);
				cardsMove += Vec2(60, 0);
			}
		}
		//从玩家手牌里移除打出去的牌
		player_self->discard(arr);
		//牌的缩进
		Node * first_node;
		for (int i = 0; i < player_self->countCards(); i++)
		{
			Node * card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			if (i == 0)
			{
				first_node = card_node;
			}
			card_node->setPositionX(first_node->getPositionX() + i * 60);
		}
	}
}
void Scene0917::buttonClicked(Ref * sender, Widget::TouchEventType type)
{
	//这里处理结束的事件
	if (type == Widget::TouchEventType::ENDED)
	{
		Button *btn = (Button *)sender;

		switch (btn->getTag())
		{
		case 100://晒
		{
			int res = 0;
			if (game->red10_hx == 's'&&game->red10_fk == 's')
			{
				res = 3;
			}
			else if (game->red10_hx == 's')
			{
				res = 2;
			}
			else if (game->red10_fk == 's')
			{
				res = 1;
			}
			player_self->show(res);
			break;
		}
		case 200://不晒
			//player_self->unShow();
			break;
		default:
			break;
		}
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);

		//显示出牌按钮
		getChildByTag(300)->getChildByTag(1)->setVisible(true);
	}
}
//触碰移动事件
void Scene0917::onTouchMoved(Touch * touch, Event *event)
{
	//获取点击的位置
	Vec2 point = touch->getLocation();

	//前提：牌已经显示出来了
	if (!game || !game->gameDidbegan)
	{
		return ;
	}


	//遍历我的每张牌
	int count = player_self->countCards();
	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的精灵节点
		Node * card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);//

																					  //获取该节点的Rect 
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectForTouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);
		//最后一张，接收事件的范围应该是自己整个区域
		if (i == count - 1)
		{
			rectForTouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectForTouch.containsPoint(point))
		{
			card_node->setPositionY(cardOriginY + 30);
			break;
		}
	}
	return ;
}

//触碰点击事件
bool Scene0917::onTouchBegin(Touch * touch, Event * event)
{
	//获取点击的位置
	Vec2 point= touch->getLocation();

	//前提：牌已经显示出来了
	if (!game || !game->gameDidbegan)
	{
		return true;
	}

	bool didTouchCard = false;//
	bool isMoveTo_ = false;
	//遍历我的每张牌
	int count = player_self->countCards();
	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的精灵节点
		Node * card_node= game->selfCards_node->getChildByTag(player_self->cards[i]);//

		//获取该节点的Rect 
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectForTouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);
		//最后一张，接收事件的范围应该是自己整个区域
		if (i == count - 1)
		{
			rectForTouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectForTouch.containsPoint(point))
		{
			if (card_node->getPositionY() > cardOriginY)
			{
				//弹出状态，需回到原始Y的位置
				card_node->setPositionY(cardOriginY);
			}
			else//弹出
			{
				card_node->setPositionY(cardOriginY + 30);
			}
			didTouchCard = true;
			break;//
		}
	}
	if (!didTouchCard)
	{
		for (int i = 0; i < count; i++)
		{
			//找到牌，并缩进
			Node * cards_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			cards_node->setPositionY(cardOriginY);
		}
	}


	return true;
}

// 开始游戏
void Scene0917::beginGame(Ref *sender, Widget::TouchEventType type) {

	//按钮点击的类型
	if (type != Widget::TouchEventType::ENDED)
		return;

	//隐藏开始按钮
	Button* btn = (Button *)sender;
	btn->setVisible(false);

	//如果之前有牌，则清除后再开始
	if (game)
	{
		//因为game创建的时候，在构造器里创建了存放自己牌的节点
		game->selfCards_node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(game);

		//之前的一些残留的内容需清除
		//比如：上一局晒的红十
		player_self->node->removeChildByTag(2);
	}

	// 1.洗牌
	int cards[54];
	game = new CardGame();
	game->gameDidbegan = true;
	game->shuffle(cards, 54);

	// 2.发牌
	player_self->initCards();
	player_right->initCards();
	player_front->initCards();
	player_left->initCards();
	Player *currentPlayer; // 记录当前操作的玩家
	int start_pos = 3; // 先发给3号
	for (int i = 0; i < 54; i++) {
		// 获取当前发牌者的真实位置
		char pos_char = getPlayerCharPosition((start_pos + i - 1) % 4 + 1);

		// ♥️3
		if (cards[i] == 41) {
			game->first = pos_char;
		}
		// ♦️10
		if (cards[i] == 22) {
			game->red10_fk = pos_char;
		}
		// ♥️10
		if (cards[i] == 48) {
			game->red10_hx = pos_char;
		}

		switch (pos_char) {
		case 's':
			currentPlayer = player_self;
			break;
		case 'r':
			currentPlayer = player_right;
			break;
		case 'f':
			currentPlayer = player_front;
			break;
		case 'l':
			currentPlayer = player_left;
			break;
		default:
			break;
		}
		currentPlayer->cards[currentPlayer->countCards()] = cards[i];
	}
	//发牌结束位置

	//显示牌的数量
	//player_self->showCardsCount();
	player_left->showCardsCount();
	player_right->showCardsCount();
	player_front->showCardsCount();


	//如果至少有一张红十在我自己这，那需要显示晒与不晒的按钮
	if (game->red10_fk == 's' || game->red10_hx == 's')
	{
		getChildByTag(100)->setVisible(true);
		getChildByTag(200)->setVisible(true);
	}
	else
	{
		//没红十
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);

		//显示出牌按钮
		getChildByTag(300)->getChildByTag(1)->setVisible(true);
	}

	//给自己的牌排序
	player_self->sortCards();

	//计算牌组放置的整体x轴居中位置
	int count = player_self->countCards();
	int mid = count / 2;//中间牌的索引位置
	float midX=(VISIBLE_SIZE.width + 180) / 2;

	// 显示自己的牌
	for (int i = 0; i < player_self->countCards(); i++) {
		//通过0-53的值，获取对应牌的精灵
		Sprite * cardSprite = game->getCardSpriteWithValue(player_self->cards[i]);
		
		cardSprite->setPosition(Vec2(midX + 60 * (i - mid) + (count%2==0?30:0),
			cardSprite->getBoundingBox().size.height / 2));
		cardOriginY = cardSprite->getPositionY();

		game->selfCards_node->addChild(cardSprite);
	}
	addChild(game->selfCards_node);
}

char Scene0917::getPlayerCharPosition(int pos)
{
	if (self_pos == 1)
	{
		if (pos == 2) return 'r';
		if (pos == 3) return 'f';
		if (pos == 4) return 'l';
	}
	else if (self_pos == 2)
	{
		if (pos == 1) return 'l';
		if (pos == 3) return 'r';
		if (pos == 4) return 'f';
	}
	else if (self_pos == 3)
	{
		if (pos == 1) return 'f';
		if (pos == 2) return 'l';
		if (pos == 4) return 'r';
	}
	else if (self_pos == 4)
	{
		if (pos == 1) return 'r';
		if (pos == 2) return 'f';
		if (pos == 3) return 'l';
	}
	return 's';//以上都不满足，则是自己
}
//加载对应玩家的UI信息
void Scene0917::loadPlayerUI(Player * player)
{
	player->pos_char= getPlayerCharPosition(player->position);

	player->createPlayerNode();
	addChild(player->node);
}
void Scene0917::close(Ref * ref)
{
	Director::getInstance()->end();
}
//任务一、显示房间号
void Scene0917::setRoomId(int roomId)
{
	Label * label = Label::createWithSystemFont(StringUtils::format("room id = %d",
		roomId), "Arial", 40);
	label->setPosition(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2);
	addChild(label);
}